<template>
  <view class="share_modal">
    <view class="cu-modal bottom-modal show">
      <view class="cu-dialog" @click.prevent="">
        <view class="padding-xl">
          <button open-type='share' class="btn item_box" @click="share">
            <!-- #ifdef MP-QQ -->
            <image class="item_img" :src="qq" mode="widthFix"></image>
            <!-- #endif -->
            <!-- #ifndef MP-QQ -->
            <image class="item_img" :src="weixin" mode="widthFix"></image>
            <!-- #endif -->
            <text class="item_title">分享给朋友</text>
          </button>
          <button class="btn item_box" @click="wechatDrawImg">
            <image class="item_img" :src="tupian" mode="widthFix"></image>
            <text class="item_title">二维码分享</text>
          </button>
          <button class="cancel" @click="close">取消</button>
        </view>
      </view>
    </view>
    <!-- 二维码分享画布 -->
    <view style='width:0px;height:0px;overflow:hidden;'>
      <canvas canvas-id="shareCanvas" style="width:984px;height:1470px"></canvas>
    </view>
  </view>
</template>

<script>
  export default {
    components: {},
    props: {
      userInfo: {
        type: Object,
      },
      itemDetail: {
        type: Object,
      },
    },
    data() {
      return {
        tupian: 'https://mtds.oss-cn-hangzhou.aliyuncs.com/taoke_rabbit/itemdetail/tupian.png',
        weixin: 'https://mtds.oss-cn-hangzhou.aliyuncs.com/taoke_rabbit/itemdetail/weixin.png',
        qq: 'https://mtds.oss-cn-hangzhou.aliyuncs.com/taoke_rabbit/itemdetail/qq.png',
        qrCode: 'https://mtds.oss-cn-hangzhou.aliyuncs.com/taoke_rabbit/share/qrcode.png', // 二维码分享图
      }
    },
    computed: {
      isDev(){
        return this.$store.state.isDev
      },
    },
    created() {
      let nickName = this.userInfo.nickName
      // #ifdef MP-WEIXIN
      wx.getImageInfo({
        src: this.qrCode,
        success: (res) => {
          const ctx = uni.createCanvasContext('shareCanvas', this)
          // 背景底图
          ctx.drawImage(res.path, 0, 0, res.width, res.height)
          // 分享者名称
          ctx.setTextAlign('center') // 文字居中
          ctx.setFillStyle('#000000') // 文字颜色：黑色
          ctx.setFontSize(40) // 文字字号
          // ctx.font = 'bold 80px PingFang SC Light';
          ctx.fillText(`您的朋友@${nickName || ''}`, res.width / 2, 1025)
          ctx.stroke()
          ctx.draw()
        }
      });
      // #endif
      
      // #ifdef MP-TOUTIAO
      tt.getImageInfo({
        src: this.qrCode,
        success: (res) => {
          const ctx = uni.createCanvasContext('shareCanvas', this)
          // 背景底图
          ctx.drawImage(res.path, 0, 0, res.width, res.height)
          // 分享者名称
          ctx.setTextAlign('center') // 文字居中
          ctx.setFillStyle('#000000') // 文字颜色：黑色
          ctx.setFontSize(40) // 文字字号
          // ctx.font = 'bold 80px PingFang SC Light';
          ctx.fillText(`您的朋友@${nickName}` || '您的朋友', res.width / 2, 1025)

          ctx.stroke()
          ctx.draw()
        }
      });
      // #endif
    },
    methods: {
      share() {
        // #ifndef H5 || APP-PLUS
        getApp().mtj.trackEvent('share_item', { // 埋点统计
          item_name: this.itemDetail.dtitle || this.itemDetail.title,
          user_id: this.userInfo.id || 0,
        });
        // #endif
        uni.share({
          provider: 'weixin',
          type: 5,
          imageUrl: this.itemDetail.imgs[0] || '',
          title: `您的好友${this.userInfo.nickName || ''}为你省去了${this.itemDetail.couponPrice || 0}元`,
          miniProgram: {
            id: 'wx12fc84193876c4e9',
            // path: `/pages/itemdetail/index?id=${this.itemDetail.id}&&goodsId=${this.itemDetail.goodsId}`,
            path: `/pages/home/index?redirect=` + encodeURIComponent(`/pages/itemdetail/index?id=${this.itemDetail.id}&&goodsId=${this.itemDetail.goodsId}`),
            type: 0,
            // webUrl: 'http://uniapp.dcloud.io'
          },
          success: res => {
            // console.log(JSON.stringify(res), 'succ');
          },
          fail: res => {
            // console.log(res, 'err');
          }
        });
      },
      wechatDrawImg() { // 微信下载二维码
        // #ifdef MP-QQ
        if(this.isDev !== 'release'){
          uni.showToast({
            icon: 'none',
            title: '功能紧张开发中',
          });
          return
        }
        // #endif
        const that = this
        wx.getSetting({
          success (res) {
            if(res.authSetting['scope.writePhotosAlbum'] === true || res.authSetting['scope.writePhotosAlbum'] === undefined){ // 授权成功或者还未发起授权
              uni.authorize({
                scope: 'scope.writePhotosAlbum',
                success: res => {
                  // 下载图片
                  uni.canvasToTempFilePath({
                    canvasId: 'shareCanvas',
                    success: res => {
                      // 下载图片
                      console.log(res.tempFilePath)
                      uni.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: res => {
                          uni.showToast({
                            title: '二维码保存成功',
                          });
                        }
                      });
                    },
                    fail: res=>{
                      uni.showToast({
                        icon: 'none',
                        title: res.errMsg,
                      });
                    }
                  }, that); // 微信需要多传入一个that
                },
                fail: res => {
                  uni.showToast({
                    icon: 'none',
                    title: '保存相册被拒绝',
                  });
                },
              })
            } else {
              wx.showModal({
                title: '用户授权',
                content: '需要获取您的保存图片权限，请确认授权，否则图片将无法保存到相册',
                success: function (tip) {
                  if (tip.confirm) {
                    wx.openSetting({
                      success: function (data) {
                        if (data.authSetting["scope.writePhotosAlbum"] === true) {
                          uni.showToast({
                            icon: 'none',
                            title: '授权成功',
                          });
                        } else {
                          uni.showToast({
                            icon: 'none',
                            title: '授权失败',
                          });
                        }
                      }
                    })
                  }
                }
              })
            }
          }
        })
      },
      ttDrawImg(){ // 头条下载二维码
        uni.authorize({
          scope: 'scope.album',
          success: res => {
            // 下载图片
            uni.canvasToTempFilePath({
              canvasId: 'shareCanvas',
              success: res => {
                console.log(res.tempFilePath)
                uni.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: res => {
                    uni.showToast({
                      title: '二维码保存成功',
                    });
                  }
                });
              },
              fail: res=>{
                uni.showToast({
                  icon: 'none',
                  title: res,
                });
              }
            });
          },
          fail: res => {
            uni.openSetting({
              success: res => {},
              fail: err => {
                uni.showToast({
                  icon: 'none',
                  title: '获取授权失败',
                });
              }
            })
          },
        })
      },
      close() {
        this.$emit('close')
      }
    }
  }
</script>

<style scoped lang="scss">
  .share_modal {
    .cu-modal {
      z-index: 3000;
      .cu-dialog {
        border-radius: 30upx 30upx 0 0;
        .padding-xl {
          .item_box {
            width: 280upx;
            height: 200upx;
            display: inline-block;
            +.item_box {
              margin-left: 50upx;
            }
            .item_img {
              vertical-align: middle;
              margin-top: 30upx;
              border-radius: 20upx;
              width: 80upx;
              height: 80upx;
            }
            .item_title {
              display: block;
              color: #294d7d;
              font-size: 30upx;
              line-height: 80upx;
            }
          }
          .cancel {
            margin: 40upx 0 20upx;
            font-size: 30upx;
          }
        }
      }
    }
  }
</style>
